<template>
  <view class="login-container">
    <view class="header-container">
      <image src="https://c.abatour.com/zimg//564049f4acbdd1ebd23d3f2f9b303ce0" mode="heightFix"></image>
      <view class="title-container">
        <view>Welcome</view>
        <view class="mt-10">您好，欢迎登录</view>
      </view>
    </view>
    <view class="content-container flex flex-col justify-between items-center">
      <view class="info-container flex flex-col justify-between items-center">
        <image class="logo-img" src="https://c.abatour.com/zimg//dbf4c8a8b6117f540d03c94fa7e7812e"></image>
        <view class="operation-container flex flex-col mt">
          <wd-button
              plain
              block
              custom-class="custom-btn-weixin-class"
              open-type="getUserInfo"
              @click="wxMiniProgramLogin"
          >
            <view class="flex items-center">
              <i class="iconfont icon-weixin fs28"></i>
              <text class="ml10">微信登录</text>
            </view>
          </wd-button>
          <wd-button plain block custom-class="custom-btn-mobile-class" class-prefix="iconfont" name="icon-jia1">
            <view class="flex items-center">
              <i class="iconfont icon-system-phone fs28"></i>
              <text class="ml10">手机号登录</text>
            </view>
          </wd-button>
        </view>
        <view class="agreement-container flex items-center" >
          <span class="flex items-center" @click="isAgree = !isAgree">
           <radio
               :value="true"
               :checked="isAgree"
               color="#1b9c61"
               style="transform: scale(0.7)"
           />
          我同意
        </span>
          <text>《用户协议》</text>
          与
          <text>《隐私协议》</text>
        </view>
      </view>
<!--      <view>456</view>-->
    </view>
    <!--  小程序端用户信息绑定 popup  -->
    <wd-popup
        v-model="bindMiniProgramInfoApp"
        position="center"
        custom-style="border-radius:12rpx;"
        closable
    >
      <view style="width:70vw" class="pd20 flex flex-col items-center">
        <wd-button
            type="primary"
            size="large"
            block
            custom-class="custom-btn-mobile-bind-class"
            open-type="getPhoneNumber"
            @getphonenumber="handleBindMiniProgramAccount"
        >
          手机号快速绑定
        </wd-button>
      </view>
    </wd-popup>
    <!--  app端用户信息绑定 popup  -->
    <wd-popup
        v-model="bindAppInfoPopup"
        position="bottom"
        :safe-area-inset-bottom="true"
        custom-style="border-radius:12rpx;"
    >
      <scroll-view
          :scroll-y="true"
          class="bind-info-container"
      >
        <view class="avatar-container">
          <wd-upload :file-list="avatarFileList" image-mode="aspectFill"></wd-upload>
        </view>
        <wd-form ref="form" :model="userBindForm">
          <wd-cell-group border>
            <wd-input
                label="用户名"
                label-width="100px"
                prop="userBindForm.userNo"
                clearable
                type="nickname"
                v-model="userBindForm.userNo"
                placeholder="请输入用户名"
                :rules="[{ required: true, message: '请填写用户名' }]"
            />
            <wd-input
                label="姓名"
                label-width="100px"
                prop="userBindForm.userName"
                clearable
                v-model="userBindForm.userName"
                placeholder="请输入姓名"
                :rules="[{ required: true, message: '请填写姓名' }]"
            />
            <wd-input
                label="手机号"
                label-width="100px"
                prop="value1"
                clearable
                type="number"
                v-model="userBindForm.phone"
                placeholder="手机号快速验证"
                :rules="[{ required: true, message: '手机号快速验证' }]"
            >
              <template #suffix>
                <view
                    v-if="!userBindForm.phone"
                    style="width: 100vw;font-size: 28rpx;color:#808080"

                >
                  手机号快速验证
                </view>
              </template>
            </wd-input>
            <wd-input
                label="密码"
                label-width="100px"
                prop="value2"
                show-password
                clearable
                v-model="userBindForm.userPwd"
                placeholder="请输入密码"
                :rules="[{ required: true, message: '请填写密码' }]"
            />
          </wd-cell-group>
          <view class="footer">
            <wd-button type="primary" size="large" @click="handleSubmit" block custom-class="custom-btn-bind-class">
              绑定
            </wd-button>
          </view>
        </wd-form>
      </scroll-view>
    </wd-popup>
    <!--    &lt;!&ndash; #ifdef MP-WEIXIN   &ndash;&gt;-->
    <!--    <wd-button icon="edit-outline" @click="wxMiniProgramLogin" open-type="getUserInfo" >微信登录</wd-button>-->
    <!--    <wd-button icon="edit-outline" @click="handleUnBindUser" >解绑</wd-button>-->
    <!--    <input-->
    <!--        v-model="nickname"-->
    <!--        class="weui-input mb-5"-->
    <!--        @blur="onNameChange"-->
    <!--        type="nickname"-->
    <!--        placeholder="请输入昵称" />-->
    <!--    &lt;!&ndash;  #endif  &ndash;&gt;-->
    <!--    <wd-popup-->
    <!--      v-model="bindAccountPopup"-->
    <!--      position="bottom"-->
    <!--      :safe-area-inset-bottom="true"-->
    <!--      :close-on-click-modal="false"-->
    <!--      :closable="true"-->
    <!--      @close="handleCloseBindAccountPopup"-->
    <!--    >-->
    <!--      <view class="bind-account-container">-->
    <!--        <wd-form ref="form" :model="userBindForm">-->
    <!--          <wd-cell-group border>-->
    <!--            <wd-input-->
    <!--                label="账号"-->
    <!--                label-width="40px"-->
    <!--                prop="value1"-->
    <!--                clearable-->
    <!--                v-model="userBindForm.userNo"-->
    <!--                placeholder="账号"-->
    <!--                :rules="[{ required: true, message: '请填写用户名' }]"-->
    <!--            />-->
    <!--            <wd-input-->
    <!--                label="密码"-->
    <!--                label-width="40px"-->
    <!--                prop="value2"-->
    <!--                show-password-->
    <!--                clearable-->
    <!--                v-model="userBindForm.userPwd"-->
    <!--                placeholder="请输入密码"-->
    <!--                :rules="[{ required: true, message: '请填写密码' }]"-->
    <!--            />-->
    <!--            <wd-input-->
    <!--                label="用户名"-->
    <!--                label-width="40px"-->
    <!--                prop="userBindForm.userName"-->
    <!--                clearable-->
    <!--                v-model="userBindForm.userPwd"-->
    <!--                placeholder="请输入昵称"-->
    <!--                :rules="[{ required: true, message: '请填写昵称' }]"-->
    <!--            />-->
    <!--          </wd-cell-group>-->
    <!--          <view class="footer">-->
    <!--            <wd-button type="primary" size="large" @click="handleSubmit" block>提交</wd-button>-->
    <!--          </view>-->
    <!--        </wd-form>-->
    <!--      </view>-->
    <!--    </wd-popup>-->
  </view>
</template>

<script setup>
  import { getCurrentInstance } from 'vue';
  const instance = getCurrentInstance() // 获取当前实例对象
  import {onLoad} from "@dcloudio/uni-app";
  import {ref} from "vue";
  import {byCodeLogin, bindAccount, unBindAccount, decodeMobileCode} from "@/api/system";
  import {useMixin} from "@/hook/useMixin";

  const {pageBack} = useMixin();

  const isAgree = ref(false);
  const bindAccountPopup = ref(false);
  const userBindForm = ref({
    userNo: "",
    userPwd: "",
    userName: "",
    headImgUrl: "",
    phone: "",
  });
  const bindAppInfoPopup = ref(false);
  const bindMiniProgramInfoApp = ref(false);
  const avatarFileList = ref([]);
  const form = ref();
  const pageLength = ref(1);

  const wxMiniProgramLogin = () => {
    if (!isAgree.value) {
      uni.showToast({
        icon: "none",
        title: "请先阅读并勾选协议"
      })
      return;
    }
    uni.login({
      success: res => {
        let {code} = res;
        handleLogin(code);
      },
      fail: err => {
        let {errMsg} = err;
        uni.showToast({
          icon: 'none',
          title: errMsg,
        })
      }
    })
  };
  const onChooseAvatar = (event) => {
    console.log(event, "event");
  };

  const onNameChange = (event) => {
    console.log("里层", event)
  };
  const handleLogin = async (code) => {
    uni.removeStorageSync("token");
    await byCodeLogin({code}).then(res => {
      let {userId, phone, userName, userNo, headImgUrl, token} = res.result;
      uni.setStorageSync("token", token);
      if (userId <= 0) {
        // #ifdef MP-WEIXIN
        bindMiniProgramInfoApp.value = true;
        // #endif
        // bindAccountPopup.value = true;
        // handleBindUser();
      } else {
        uni.setStorageSync("userInfo", {
          userId,
          userNo,
          userName,
          phone,
          headImgUrl,
        });
        // ai 视旅 需要额外登陆获取token
        // if (instance) {
        //   shiluLogin(phone,code)
        // } else {
          pageBack(pageLength.value);
        // }
      }
    });
  }
  const handleBindUser = async (userNo, userPwd, userName, headImgUrl, phone) => {
    await bindAccount({
      userNo: "17581709111",
      userPwd: "123lxh",
      userName: "zz",
      headImgUrl: "",
      phone: "17581709115",
    }).then(res => {
      let {result:token} = res;
      uni.setStorageSync("token", token);

      console.log(res, 'res')
    })
  };

  const handleUnBindUser = async () => {
    await unBindAccount({accountId: 3}).then(res => {
      console.log(res, 'res');
      let {result} = res;
      if (result) {
        uni.showToast({
          icon: "none",
          title: "解绑成功"
        });
      }
    });
  };
  const handleSubmit = () => {
  };
  const handleCloseBindAccountPopup = () => {

  };
  const handleBindMiniProgramAccount = async (event) => {
    console.log(event, "event-handleBindMiniProgramAccount");
    let {code, errMsg} = event;
    if (!code) {
      uni.showToast({
        icon: "none",
        title: errMsg
      })
    }
    await decodeMobileCode({code}).then(res => {
      let {userId, phone, userName, userNo, headImgUrl, token} = res.result;
      uni.setStorageSync("userInfo", {
        userId,
        userNo,
        userName,
        phone,
        headImgUrl,
      });
      // ai 视旅 需要额外登陆获取token
      // if (instance) {
      //   uni.login({
      //     success: res => {
      //       let {code} = res;
      //       shiluLogin(phone,code)
      //     },
      //     fail: err => {
      //       let {errMsg} = err;
      //       uni.showToast({
      //         icon: 'none',
      //         title: errMsg,
      //       })
      //     }
      //   })
      // } else {
        pageBack(pageLength.value);
      // }
    })
  };
  const shiluLogin = (phoneCode, loginCode) =>{
    // 访问全局属性 $aiRequest
    instance.appContext.config.globalProperties.$aiRequest({
      url: `/login/applet`,
      method: "POST",
      header: {
        "Content-Type": "application/json",
      },
      params: {
        phoneCode: phoneCode, //手机号code
        loginCode: loginCode, //登录code
      },
    })
    .then((res) => {
      if (res.success) {
          //没有多个账号直接登录
          instance.appContext.config.globalProperties.$getUserInfo(res, {}, 1);
          // 跳转
          pageBack(pageLength.value);
      }
    });
  }
  onLoad(() => {
    pageLength.value = getCurrentPages().length;
  });

</script>

<style lang="scss" scoped>
.bind-account-container {
  height: 70vh;
  overflow: hidden;
}

.login-container {
  .header-container {
    position: relative;
    width: 100%;
    height: 582rpx;

    image {
      width: 100%;
      height: 100%;
    }

    .title-container {
      position: absolute;
      top: 200rpx;
      width: 750rpx;
      font-size: 42rpx;
      text-align: center;
      font-weight: bold;
      color: #EEF0DF;
    }
  }

  .content-container {
    position: absolute;
    top: 350rpx;
    width: 100%;
    height: calc(100% - 350rpx);
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    background: #FFFFFF;

    .info-container {
      .logo-img {
        margin-top: 152rpx;
        width: 208rpx;
        height: 208rpx;
        border-radius: 50%;
      }

      .operation-container {
        margin-top: 77rpx;

        :deep() {
          .custom-btn-weixin-class {
            width: 80vw;
            height: 70rpx;
            border-radius: 10.5rpx !important;
            border: 1rpx solid #1B9C61;
            background: #1B9C61;
            color: #EEF0DF;
            font-size: 30rpx;
            margin-bottom: 28rpx;
          }

          .custom-btn-mobile-class {
            width: 80vw;
            height: 70rpx;
            border-radius: 10.5rpx !important;
            border: 1rpx solid #C0C2B3;
            background: #FFFFFF;
            color: #2B2B24;
            font-size: 30rpx;
          }
        }
      }

      .agreement-container {
        margin-top: 83rpx;
        font-size: 25rpx;

        text {
          color: #AA5413;
        }
      }
    }
  }

  .bind-info-container {
    height: 40vh;
    padding: 20rpx;
    white-space: nowrap;
    box-sizing: border-box;

    .avatar-container {
      display: flex;
      justify-content: center;
    }
  }

  :deep() {
    .custom-btn-bind-class {
      height: 70rpx;
      border-radius: 10.5rpx !important;
      border: 1rpx solid #1B9C61 !important;
      background: #1B9C61 !important;
      color: #EEF0DF;
      font-size: 30rpx;
      margin-bottom: 28rpx;
    }

    .custom-btn-mobile-bind-class {
      height: 70rpx;
      border-radius: 10.5rpx !important;
      border: 1rpx solid #1B9C61 !important;
      background: #1B9C61 !important;
      color: #EEF0DF;
      font-size: 30rpx;
    }
  }
}

</style>
